// 全局变量存储当前选中的 sheet
let currentSheet = '';
let allResults = null;

// 从 cookie 获取用户 ID
function getUserId() {
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
        const [name, value] = cookie.trim().split('=');
        if (name === 'user_id') {
            return value;
        }
    }
    return null;
}

// 创建并显示Toast提示
function showToast(title, message, type = 'warning') {
    const toastContainer = document.getElementById('toastContainer');
    const toastId = 'toast-' + Date.now();
    
    const toastHtml = `
        <div class="toast" role="alert" id="${toastId}">
            <div class="toast-header ${type === 'error' ? 'bg-danger text-white' : 'bg-warning'}">
                <i class="bi ${type === 'error' ? 'bi-exclamation-triangle-fill' : 'bi-exclamation-triangle'} me-2"></i>
                <strong class="me-auto">${title}</strong>
                <button type="button" class="btn-close ${type === 'error' ? 'btn-close-white' : ''}" data-bs-dismiss="toast"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    
    toastContainer.insertAdjacentHTML('beforeend', toastHtml);
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        autohide: type !== 'error',
        delay: 5000
    });
    
    // 监听toast隐藏事件，移除DOM元素
    toastElement.addEventListener('hidden.bs.toast', () => {
        toastElement.remove();
    });
    
    toast.show();
}

// 检查并显示工作表错误
function checkSheetErrors() {
    let hasErrors = false;
    let errorMessages = [];

    // 遍历所有工作表检查错误
    Object.entries(allResults).forEach(([sheetName, result]) => {
        if (result.error_count && result.error_count > 0) {
            hasErrors = true;
            let sheetErrors = `<strong>工作表 "${sheetName}"</strong>`;
            if (result.errors && result.errors.length > 0) {
                sheetErrors += '<ul class="mb-0 ps-3">';
                result.errors.forEach(error => {
                    sheetErrors += `<li>${error.message}</li>`;
                });
                sheetErrors += '</ul>';
            }
            errorMessages.push(sheetErrors);
        }
    });

    // 如果有错误，显示Toast提示
    if (hasErrors) {
        errorMessages.forEach((message, index) => {
            // 延迟显示每个Toast，避免重叠
            setTimeout(() => {
                showToast('数据处理提示', message);
            }, index * 300);
        });
    }
}

// 初始化加载数据
async function initializeSheets() {
    try {
        const userId = getUserId();
        if (!userId) {
            throw new Error('未找到用户标识');
        }

        // 获取所有 sheet 的处理结果
        const response = await fetch(`data/${userId}/all_results.json`);
        if (!response.ok) {
            throw new Error('Failed to load sheet data');
        }
        
        allResults = await response.json();
        
        // 检查错误信息
        checkSheetErrors();
        
        // 创建 sheet tabs
        const sheetTabs = document.getElementById('sheetTabs');
        Object.keys(allResults).forEach((sheetName, index) => {
            const li = document.createElement('li');
            li.className = 'nav-item';
            
            const a = document.createElement('a');
            a.className = `nav-link ${index === 0 ? 'active' : ''}`;
            a.textContent = sheetName;
            a.onclick = () => switchSheet(sheetName);
            
            li.appendChild(a);
            sheetTabs.appendChild(li);
        });
        
        // 加载第一个 sheet 的数据
        if (Object.keys(allResults).length > 0) {
            currentSheet = Object.keys(allResults)[0];
            await loadSheetData(currentSheet);
        }
    } catch (error) {
        console.error('Error initializing sheets:', error);
        showToast('加载失败', '加载数据失败，请刷新页面重试', 'error');
    }
}

// 切换 sheet
async function switchSheet(sheetName) {
    if (currentSheet === sheetName) return;
    
    // 更新 tab 激活状态
    document.querySelectorAll('#sheetTabs .nav-link').forEach(tab => {
        tab.classList.remove('active');
        if (tab.textContent === sheetName) {
            tab.classList.add('active');
        }
    });
    
    currentSheet = sheetName;
    await loadSheetData(sheetName);
}

// 加载指定 sheet 的数据
async function loadSheetData(sheetName) {
    try {
        const sheetResult = allResults[sheetName];
        if (!sheetResult || sheetResult.status !== 'success') {
            throw new Error(`工作表 "${sheetName}" 数据不可用`);
        }
        
        // 加载考试详情数据
        const examDetailsResponse = await fetch(`data/${sheetResult.exam_details}`);
        const examDetails = await examDetailsResponse.json();
        
        // 加载学生详情数据
        const stuDetailsResponse = await fetch(`data/${sheetResult.stu_details}`);
        const stuDetails = await stuDetailsResponse.json();
        
        // 更新页面数据
        updateExamList(examDetails);
        updateStudentList(stuDetails);
        
        // 触发默认选择第一个考试
        const examSelect = document.getElementById('exam-select');
        if (examSelect.options.length > 0) {
            examSelect.selectedIndex = 0;
            examSelect.dispatchEvent(new Event('change'));
        }
    } catch (error) {
        console.error('Error loading sheet data:', error);
        showToast('加载失败', error.message, 'error');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initializeSheets);
